package cn.hackcloud.mq;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ProducerService {
    private DefaultMQProducer producer;
    @Value("${rocketmq.group}")
    private String groupName;
    @Value("${rocketmq.nameAddr}")
    private String nameAddr;

    @PostConstruct
    public void init() {
        producer = new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(nameAddr);
        producer.setRetryTimesWhenSendFailed(3);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void send(String topic, String tag, String key, String body) {
        Message message = new Message(topic, tag, key, body.getBytes());
        try {
            producer.send(message);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    @PreDestroy
    public void destory() {
        producer.shutdown();
    }
}
